package com.sptpc.learnspring.service;

import com.sptpc.learnspring.common.OrderState;
import com.sptpc.learnspring.controller.request.ClearOrderRequest;
import com.sptpc.learnspring.controller.request.NewOrderRequest;
import com.sptpc.learnspring.model.Drink;
import com.sptpc.learnspring.model.Order;
import com.sptpc.learnspring.repository.DrinkRepository;
import com.sptpc.learnspring.repository.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private DrinkRepository drinkRepository;

    public Order saveOrder(String customer, Drink... drinks) {
        Order order = Order.builder()
                .customer(customer)
                .items(new ArrayList<>(Arrays.asList(drinks)))
                .state(OrderState.INIT).build();
        return orderRepository.save(order);
    }

    public Order saveOrder(NewOrderRequest orderRequest) {
        var drinks = new ArrayList<Drink>();
        for (Long drinkId : orderRequest.getDrinks()){
            drinks.add(drinkRepository.findById(drinkId).orElse(null));
        }
        Order order = Order.builder()
                .customer(orderRequest.getCustomer())
                .items(drinks)
                .state(OrderState.INIT).build();
        return orderRepository.save(order);
    }

    public List<Order> getOrders(String customer) {

        return orderRepository.findOrdersByCustomerLike(customer);
    }

    public List<Order> getOrdersByTime(LocalDateTime startTime, LocalDateTime endTime, String customer) {

        return orderRepository.findOrdersByCreateTimeBetweenAndCustomer(startTime, endTime, customer);
    }

    public boolean changeState(Order oldOrder, OrderState state){
        if (state.compareTo(oldOrder.getState()) <= 0){
            log.warn("状态不能从{}到{}",oldOrder.getState(),state);
            return false;
        }
        oldOrder.setState(state);
        Order order = orderRepository.saveAndFlush(oldOrder);
        log.info("更改后的订单{}", order);
        return true;
    }

    public Order clearOrder(ClearOrderRequest clearOrderRequest) {
        Order oldOrder = orderRepository.findOrderById(clearOrderRequest.getOrderId());
        oldOrder.setState(OrderState.CANCELLED);
        return orderRepository.saveAndFlush(oldOrder);
    }

    public void delete(long orderId) {
        orderRepository.deleteById(orderId);
        log.info("删除成功");
    }
}
